package com.zhongcw.test.spring.boot.validation.exception;

import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ZCW
 * @createTime 2018/4/12
 * @lastUpdateTime 2018/4/12 ZCW
 */
//@RestControllerAdvice
public class ValidExceptionHandler {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Map handleException(MethodArgumentNotValidException exception){

        String errorMsg = exception.getBindingResult().getFieldErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .findFirst()
                .orElse(exception.getMessage());

        Map<String,String> result= new HashMap<>(1);
        result.put("code","400");
        result.put("msg",errorMsg);

        return result;
    }
}
